<template>
  <div class="menu_mange">
    <!-- 查询条件区域 -->
    <div class="search-container">
      <el-form :model="state.queryData" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="销售订单号">
              <el-input v-model="state.queryData.SalesCode" placeholder="请输入销售订单号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户">
              <el-select
                v-model="state.queryData.cCusCode"
                placeholder="请选择客户"
                filterable
              >
                <el-option
                  v-for="item in cubasdoc.data"
                  :key="item.cCusCode"
                  :label="item.ccusname"
                  :value="item.cCusCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="业务员">
              <el-select
                v-model="state.queryData.salesman"
                placeholder="请选择业务员"
              >
                <el-option
                  v-for="item in state.userList"
                  :key="item.cPsn_Num"
                  :label="item.cPsn_Name"
                  :value="item.cPsn_Num"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="执行情况">
              <el-select v-model="state.queryData.FHZX" placeholder="请选择执行情况">
                <el-option label="发货已完成" value="发货已完成" />
                <el-option label="发货未完成" value="发货未完成" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="制单时间">
              <el-date-picker
                v-model="state.queryData.dbdate"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="btn-group">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="danger" @click="handleReset">重置</el-button>
        </el-row>
      </el-form>
    </div>

    <!-- 发货单列表 -->
    <div class="table-container">
      <h3>发货单列表</h3>
      <el-table
        ref="TAdaptivePageDemo"
        :data="state.table.data"
        :row-key="getRowKey"
        height="260"
        border
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" fixed width="55" />
        <el-table-column prop="ccode" label="发货单号" width="150" />
        <el-table-column prop="ddate" label="单据日期" width="100">
          <template #default="{ row }">
            <el-text type="primary">{{ parseTime(row.ddate, '{y}-{m}-{d}') }}</el-text>
          </template>
        </el-table-column>
        <el-table-column prop="cCusName" label="客户名称" width="140" />
        <el-table-column prop="DeliveryMethod" label="发货方式" width="100" />
        <el-table-column prop="contacts" label="客户联系人" width="100" />
        <el-table-column prop="Telephone" label="联系电话" width="100" />
        <el-table-column prop="address" label="客户地址" width="130" />
        <el-table-column prop="number" label="物流金额" width="90" />
        <el-table-column prop="logistics" label="物流公司" width="100" />
        <el-table-column prop="courierNumber" label="快递单号" width="100" />
        <el-table-column prop="cDepName" label="部门" width="100" />
        <el-table-column prop="depcode" label="部门编码" width="100" />
        <el-table-column prop="cPsn_Name" label="业务员" width="90" />
        <el-table-column prop="cCusCodeID" label="客户编码" width="100" />
        <el-table-column prop="ExchangeRate" label="汇率" width="80" />
        <el-table-column prop="currency" label="币种" width="100" />
        <el-table-column prop="SalesType" label="销售类型" width="100" />
        <el-table-column prop="confirm" label="是否发货确认" width="110" />
        <el-table-column prop="StateID" label="单据状态" width="100" />
        <el-table-column prop="Iclose" label="锁定状态" width="100" />
        <el-table-column prop="remarksT" label="表头备注" show-overflow-tooltip width="100" />
        <el-table-column prop="Preparer" label="制单人" width="100" />
        <el-table-column prop="Pdate" label="制单时间" width="100" />
        <el-table-column prop="Modified" label="修改人" width="100" />
        <el-table-column prop="Mdate" label="修改时间" width="100" />
        <el-table-column prop="ReviewedBy" label="审核人" width="100" />
        <el-table-column prop="AuditTime" label="审核时间" width="100" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="state.table.currentPage"
          v-model:page-size="state.table.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="state.table.total"
          @size-change="handlesSizeChange"
          @current-change="handlesCurrentChange"
        />
      </div>
    </div>

    <!-- 明细列表 -->
    <div class="detail-container">
      <h3>明细</h3>
      <el-table
        ref="singleEditTSelectTable"
        :data="state.table_d.data"
        height="260"
        border
        @selection-change="selectionDChange"
      >
        <el-table-column type="selection" fixed width="55" />
        <el-table-column prop="cInvCode" label="存货编码" min-width="120" />
        <el-table-column prop="cInvName" label="存货名称" min-width="200" />
        <el-table-column prop="cInvStd" label="规格型号" min-width="120" />
        <el-table-column prop="cInvCodeK" label="客户存货编码" min-width="120" />
        <el-table-column prop="cInvNameK" label="客户存货名称" min-width="120" />
        <el-table-column prop="cInvStdK" label="客户存货规格型号" min-width="160" />
        <el-table-column prop="UnitPrice" label="单价" min-width="180" />
        <el-table-column prop="quantity" label="数量" min-width="180" />
        <el-table-column prop="taxRate" label="税率" min-width="180" />
        <el-table-column prop="deliver" label="初始预发货日期" min-width="160" />
        <el-table-column prop="deliverDate" label="实际预发货日期" min-width="160" />
        <el-table-column prop="Xingguan" label="是否关闭" min-width="160" />
        <el-table-column prop="MOQ" label="订单MOQ" min-width="160" />
        <el-table-column prop="DeliveryTime" label="客户停产日期" min-width="160" />
        <el-table-column prop="MinimumTime" label="最短交期(天)" min-width="160" />
        <el-table-column prop="MaterialShutdown" label="物料停产日期" min-width="160" />
        <el-table-column prop="SafetyStock" label="安全库存量" min-width="180" />
        <el-table-column prop="TransitionStatus" label="转产状态" min-width="160" />
        <el-table-column prop="makeUp" label="拼板数" min-width="180" />
        <el-table-column prop="completeDate" label="预生产完工日期" min-width="160" />
        <el-table-column prop="cycle" label="日均产量" min-width="180" />
        <el-table-column prop="Productivity" label="产品难度系数" min-width="160" />
        <el-table-column prop="ActualCycle" label="标准产品产能" min-width="160" />
        <el-table-column prop="ActualCycleJ" label="交付日总产能" min-width="160" />
        <el-table-column prop="CustomerOrder" label="客户订单号" min-width="160" />
        <el-table-column prop="remarks" label="备注" min-width="160" />
        <el-table-column prop="ContractID" label="标的ID" min-width="160" />
        <el-table-column prop="ContractNo" label="合同号" min-width="160" />
      </el-table>
    </div>

    <!-- 按钮区域 -->
    <div class="footer-btn">
      <el-button type="primary" :disabled="!state.idds.length" @click="addTableDatas">确定选择</el-button>
    </div>
  </div>
</template>

<script setup lang="tsx" name="selection">
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { debounce, parseTime } from '@/utils/util'
import { cubasdocStore } from '@/stores/modules/cubasdoc'
import { findbaseBasicManage, findBoxData, getContractList } from '@/api/base'
import { ComboBoxDataList, salesOrderList, salesOrderListViewsCZ } from '@/api/sale_deliver'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['changeTables'])
// 获取ref
const TAdaptivePageDemo: any = ref(null)

// 选择复选框
const selectionChange = (val: any) => {
  let isCheck = 0

  //判断同一公司及同一联系人同一地址才能合并发货
  if (state.chooseModel.length > 0) {
    let company = state.chooseModel[0].cCusCodeID
    let person = state.chooseModel[0].contacts
    let address = state.chooseModel[0].address
    for (let i = 0; i < val.length; i++) {
      if (company != val[i].cCusCodeID || person != val[i].contacts || address!=val[i].address) {
        isCheck++
        ElMessage.error('同一客户同一联系人同一地址才能合并退货')
        // 取消选中不满足条件的行
        const tableRef = TAdaptivePageDemo.value
        if (tableRef) {
          tableRef.toggleRowSelection(val[i], false)
        }
      }
    }
  }
  if (isCheck == 0) state.chooseModel = val
  state.ids = val.map((item: any) => item.Sid)

  let join = ''
  if (state.ids.length == 1) {
    join = state.ids[0] + ','
  } else {
    join = state.ids.join(',')
  }
  //查询物料详情
  salesOrderListViewsCZ({
    Sid: join,
    table: 'SendAndReturnView'
  }).then(res => {
    state.table_d.data = res.Rows
  })
}

// 翻页选中的唯一值
const getRowKey = row => {
  return row.Sid
}

const addTableDatas = row => {
  emit('changeTables', state.idds, state.chooseModel[0])
  // 清除选中状态
  const tableRef = TAdaptivePageDemo.value
  if (tableRef) {
    tableRef.clearSelection()
  }
  const detailTableRef = singleEditTSelectTable.value
  if (detailTableRef) {
    detailTableRef.clearSelection()
  }
  state.idds = []
  state.chooseModel = []
}

const selectionDChange = row => {
  state.idds = row

}

const state: any = reactive({
  ids: [],
  idds: [],
  chooseModel: [],
  invOptions: [],
  options: [],
  loading: false,
  queryData: {
    StateID: '已审核'
  },
  table: {
    currentPage: 1,
    pageSize: 20,
    total: 0,
    // 接口返回数据
    data: []
  },
  addDialog: {
    title: '新增',
    visible: false,
    loading: false,
    formData: {
      ddate: parseTime(new Date(), '{y}-{m}-{d}'),
      // BodyJson:[],
      taxrate: 13,
      repair: '否',
      SalesType: '分期付款',
      TranType: '分期付款',
      salesman: '101',
      cDepName: '推广服务部',
      depcode: '05',
      contacts: '王晓峰',
      Telephone: '13323334545',
      DeliveryMethod: '快递',
      PackingMethod: '自备包装',
      remarks: '客户要求私密发货',
      ExchangeRate: 6.5,
      Pdate: parseTime(new Date(), '{y}/{m}/{d} {h}:{i}:{s}'),
      Preparer: '邹涛',
      change: '否',
      StateID: '自由'
    },
    rules: {
      cCusCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
      ContractNo: [{ required: true, message: '请选择合同号', trigger: 'blur' }],
      repair: [{ required: true, message: '请选择是否补录', trigger: 'change' }],
      SalesType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
      // SalesCode: [{ required: true, message: "请输入销售订单号", trigger: "blur" }],
      TranType: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
      ddate: [{ required: true, message: '请选择单据时间', trigger: 'change' }],
      salesman: [{ required: true, message: '请选择业务员', trigger: 'change' }],

      taxrate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
      ExchangeRate: [{ required: true, message: '请输入汇率', trigger: 'blur' }]
    }
  },
  table_d: {
    rules: {},
    firstColumn: { type: 'selection', fixed: true },
    data: [],
    columns: [
      {
        prop: 'cInvCode',
        label: '存货编码',
        placeholder: '请选择存货',
        minWidth: '120'
      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200'
      },
      {
        prop: 'cInvStd',
        minWidth: '120',
        label: '规格型号'
      },

      {
        prop: 'cInvCodeK',
        minWidth: '120',
        label: '客户存货编码'
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称'
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号'
      },
      {
        prop: 'UnitPrice',
        label: '单价',
        minWidth: '180'
      },
      {
        prop: 'quantity',
        label: '数量',
        minWidth: '180'
      },
      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180'
      },

      {
        prop: 'deliver',
        minWidth: '160',
        label: '初始预发货日期'
      },
      {
        prop: 'deliverDate',
        minWidth: '160',
        label: '实际预发货日期'
      },
      {
        prop: 'Xingguan',
        minWidth: '160',
        label: '是否关闭'
      },

      {
        prop: 'MOQ',
        minWidth: '160',
        label: '订单MOQ'
      },

      {
        prop: 'DeliveryTime',
        minWidth: '160',
        label: '客户停产日期'
      },

      {
        prop: 'MinimumTime',
        minWidth: '160',
        label: '最短交期(天)'
      },

      {
        prop: 'MaterialShutdown',
        minWidth: '160',
        label: '物料停产日期'
      },
      {
        prop: 'SafetyStock',
        minWidth: '180',
        label: '安全库存量'
      },
      {
        prop: 'TransitionStatus',
        minWidth: '160',
        label: '转产状态'
      },
      {
        prop: 'makeUp',
        label: '拼板数',
        // headerRequired: true,
        minWidth: '180'
      },

      {
        prop: 'completeDate',
        minWidth: '160',
        label: '预生产完工日期'
      },
      {
        prop: 'cycle',
        minWidth: '180',
        label: '日均产量'
      },
      {
        prop: 'Productivity',
        minWidth: '160',
        label: '产品难度系数'
      },

      {
        prop: 'ActualCycle',
        minWidth: '160',
        label: '标准产品产能'
      },
      {
        prop: 'ActualCycleJ',
        minWidth: '160',
        label: '交付日总产能'
      },
      {
        prop: 'CustomerOrder',
        minWidth: '160',
        label: '客户订单号'
      },

      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注'
      },
      {
        prop: 'ContractID',
        minWidth: '160',
        label: '标的ID'
      },
      {
        prop: 'ContractNo',
        minWidth: '160',
        label: '合同号'
      }
    ]
    // 表格内操作列
  },
  userList: [],
  invList: []
})


// 最终参数获取
const getQueryData = computed(() => {
  let queryList = []
  const res = toRefs(state.queryData)
  Object.keys(res).forEach(item => {

    let data = {}
    if (res[item].value) {
      if (item === 'dbdate') {
        data = {
          field: 'Pdate',
          op: 'and',
          value: res[item].value[0],
          type: 'date'
        }
        queryList.push(data)
        data = {
          field: 'Pdateend',
          op: 'and',
          value: res[item].value[1],
          type: 'date'
        }
        queryList.push(data)
      } else {
        data = {
          field: item,
          op: 'and',
          value: res[item].value,
          type: 'text'
        }
        queryList.push(data)
      }
    }
  })
  queryList.push({
    field: 'StateID',
    op: 'and',
    value: '已审核',
    type: 'text'
  })
  let dept = {
    field: 'depcode',
    op: 'and',
    value: '08',
    type: 'hidden'
  }
  queryList.push(dept)

  return queryList.length > 0 ? { rules: queryList, op: 'and' } : null
})
// 点击查询按钮
const conditionEnter = (data: any) => {
  state.queryData = data
  getData()
}

// 自定义查询方法
const handleSearch = () => {
  getData()
}

// 重置查询条件
const handleReset = () => {
  state.queryData = {
    StateID: '已审核'
  }
  getData()
}
onMounted(() => {
  getUserList()
  getInvList()
  findContracts()
  getData()
})
// 获取菜单数据
const getData = async () => {
  let queryData = {
    table: 'SendAndReturnView',
    name: 'undefined',
    value: 'undefined',
    DoType: 0,
    KJTJ: ''
  }
  if (getQueryData.value) {

    queryData.KJTJ = JSON.stringify(getQueryData.value)
  }
  const formData = new FormData()
  formData.append('page', state.table.currentPage) // 添加字段
  formData.append('pagesize', state.table.pageSize) // 添加另一个字段
  const { Rows, Total } = await salesOrderList(queryData, formData)
  state.table.data = Rows
  state.table.total = Total
}
// 页面大小
const handlesSizeChange = (val: any) => {
  state.table.pageSize = val
  getData()
}
// 页码
const handlesCurrentChange = (val: any) => {
  state.table.currentPage = val
  getData()
}

const singleEditTSelectTable: any = ref(null)

const cubasdoc = cubasdocStore()

// 编辑单元格监听事件 - 保留但可能不再需要
const handleEvent = (type, val, index) => {

}

// 错误校验提示 - 保留但可能不再需要
const validateError = list => {
  list.map(val => {
    setTimeout(() => {
      ElMessage.error(`${val}是必填项！`)
    }, 100)
  })
}

//查询存货 -- 增加防抖函数 - 保留但可能不再需要
const remoteMethod = debounce(
  async query => {
    if (query) {
      state.options = state.invList.filter(item => {
        return (
          item.name.toLowerCase().includes(query.toLowerCase()) ||
          item.id.toLowerCase().includes(query.toLowerCase())
        )
      })
    } else {
      state.options = state.invList
    }
  },
  200,
  false
)

//存货选择 - 保留但可能不再需要
async function updateInv(e, row) {
  //过滤客户
  let invoptions = state.invList.filter(its => {
    return its.id.toLowerCase().includes(e.toLowerCase())
  })[0]
  if (invoptions) {
    //赋值
    row.cInvName = invoptions.name
  }
}

//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

//查询存货信息
const getInvList = async () => {
  let Rows = await findBoxData()
  state.invList = Rows


  state.invOptions = await ComboBoxDataList()
}

//查询合同信息
async function findContracts() {
  let queryData = {
    ContractType: null,
    CustCode: null,
    CustName: null,
    ContractNum: null,
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null
  }
  //获取合同信息
  let contractData = await getContractList(queryData)
  cubasdoc.setContractList(contractData.Data)
}
</script>

<style scoped>
.menu_mange {
  padding: 20px;
}

.search-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.btn-group {
  margin-top: 10px;
}

.table-container,
.detail-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.table-container h3,
.detail-container h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.footer-btn {
  margin-top: 16px;
  display: flex;
  justify-content: flex-start;
}
</style>
